<!DOCTYPT html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Fetch、filter、正则表达式实现快速古诗匹配</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<form class="search-form">
<input type="text" class="search" placeholder="诗人名字，关键字">
<ul class="suggestion">
<li>输入词句，找一首诗</li>
<li></li>
</ul>
</form>
<script>
    const endpoint =
      'https://gist.githubusercontent.com/liyuechun/f00bb31fb8f46ee0a283a4d182f691b4/raw/3ea4b427917048cdc596b38b67b5ed664605b76d/TangPoetry.json';
	  const poetrys=[];
	  fetch(endpoint)
	  .then(res=>{return res.json();}  
	  )
	  .then(data=>{
	  poetrys.push(...data);
	  });
	function findMatches(word,poetrys){
	return poetrys.filter(poet=>{
	const regx=new RegExp(word,'gi');
	const author=poet.detail_author.join('');
	return poet.detail_text.match(regx)||poet.title.match(regx)||author.match(regx);
	})
	}
	
	function displayMatches(){
	const matches=findMatches(this.value,poetrys);
	const regx=new RegExp(this.value,'gi');
	const html=matches.map(poet=>{
	const text=poet.detail_text.replace(regx,`<span class="h1">${this.value}</span>`);
	const title = poet.title.replace(regx, `<span class="hl">${ this.value }</span>`);
    const detail_author = poet.detail_author[0].replace(regx, `<span class="hl">${ this.value }</span>`);
	   return `
      <li>
        <span class="poet">${ text }</span>
        <span class="title">${ title } - ${ detail_author }</span>
      </li>
    `;
	}).join('');
	console.log(html);
	suggestion.innerHTML=html;
	}
	const search=document.querySelector('.search');
	const suggestion=document.querySelector('.suggestion');
	search.addEventListener('change',displayMatches);
	search.addEventListener('keyup',displayMatches);
	console.log(poetrys);
</script>
</body>
<html>